package com.ssm.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 实现对请求头处理的 servlet 过滤器
 * 它负责将请求头转换成我们新定义的 token
 */
public class RequestHeaderProcessingFilter extends AbstractAuthenticationProcessingFilter {
    private String usernameHeader = "j_username";
    private String passwordHeader = "j_password";
    private String signatureHeader = "j_signature";

    /**
     * {@inheritDoc}
     * tomcat拉起的时候回来此处进行加载登录的URL，前提是该类配置到了security.xml中，并且配置before
     * <security:custom-filter ref="requestHeaderFilter" before="FORM_LOGIN_FILTER"/>
     */
    protected RequestHeaderProcessingFilter() {
        super("/j_spring_security_filter");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String username = request.getHeader(usernameHeader);
        String password = request.getHeader(passwordHeader);
        String signature = request.getHeader(signatureHeader);

        SignedUsernamePasswordAuthenticationToken authRequest = new SignedUsernamePasswordAuthenticationToken(username, password, signature);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    /**
     * @return the usernameHeader
     */
    public String getUsernameHeader() {
        return usernameHeader;
    }

    /**
     * @param usernameHeader the usernameHeader to set
     */
    public void setUsernameHeader(String usernameHeader) {
        this.usernameHeader = usernameHeader;
    }

    /**
     * @return the passwordHeader
     */
    public String getPasswordHeader() {
        return passwordHeader;
    }

    /**
     * @param passwordHeader the passwordHeader to set
     */
    public void setPasswordHeader(String passwordHeader) {
        this.passwordHeader = passwordHeader;
    }

    /**
     * @return the signatureHeader
     */
    public String getSignatureHeader() {
        return signatureHeader;
    }

    /**
     * @param signatureHeader the signatureHeader to set
     */
    public void setSignatureHeader(String signatureHeader) {
        this.signatureHeader = signatureHeader;
    }
}
